package com.ly.hotel.spainterface.jg.view;

import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jg.adapter.MassageBillAdapter;
import com.ly.hotel.spainterface.jg.bean.OnSwipeCardListener;
import com.ly.hotel.spainterface.jg.bean.gson.bill.SelfConsumeRecord;
import com.ly.hotel.spainterface.jg.bean.gson.bill.SelfTableCodeInPara;
import com.ly.hotel.spainterface.jg.bean.gson.bill.SelfTableCodeOutPara;
import com.ly.hotel.spainterface.jg.bean.gson.bill.SelfTableCodeResult;
import com.ly.hotel.spainterface.jg.bean.gson.handcard.HandCard;
import com.ly.hotel.spainterface.jg.bean.gson.handcard.HandCardResult;
import com.ly.hotel.spainterface.jg.bean.gson.postJson.TableChipPara;
import com.ly.hotel.spainterface.jg.utils.DecToHexUtils;
import com.ly.hotel.spainterface.jg.utils.GsonUtils;
import com.ly.hotel.spainterface.jg.utils.OkHttpUtils;
import com.ly.hotel.spainterface.jg.utils.SwipeCardUtils;

import java.util.List;

/**
 * Created by ThinkPad on 2018/3/12.
 */

public class CustomQueryBillDialog extends DialogFragment implements OnSwipeCardListener {

    private String cardIdHex;
    private String cashierIP;
    private String cashierPORT;
    private CustomLoadingDialog loadingDialog;
    private int[] judgeNum = {0,1,2};// 0为手牌接口，1为账单查询接口
    private String tvName;
    private String categoryName;
    private String tableCode;// 手牌号
    private ListView goodsBillListView;
    private TextView handCard;
    private TextView totalPrice;
    private TextView billIsNoneTips;
    private SwipeCardUtils swipeCardUtils;
    private TextView totalTips;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String resultString = msg.obj.toString();
                    if(msg.arg1 == judgeNum[0]){
                        swipeCardUtils.cancelBandNo(false);
                        Log.d("JgActivity", "手牌号转ID号接口返回：" + resultString);
                        HandCardResult handCardResult = GsonUtils.parseSimpleJson(resultString,HandCardResult.class);
                        if(handCardResult.isSuccess()){
                            HandCard handCard = handCardResult.getResult();
                            String tableChipId = handCard.getTableChipId();// 转成16进制的芯片号
                            // 返回的手牌号
                            tableCode = handCard.getTableCode();
                            Log.d("getBandNo", tableChipId + "-" + tableCode);
                            if(tableChipId != null && tableCode != null){
                                queryBill(tableCode);
                            }else{
                                loadingDialog.close();
                                dismiss();// 关闭窗口
                                CustomToast customToast = CustomToast.makeText(getActivity(),"非客人手牌，请联系服务员！", Toast.LENGTH_LONG,false);
                                customToast.setGravity(Gravity.CENTER,0,0);
                                customToast.showMyToast(5000);
                            }
                        }
                    }else if(msg.arg1 == judgeNum[1]){
                        Log.d("JgActivity", "账单接口返回：" + resultString);
                        SelfTableCodeResult selfTableCodeResult = GsonUtils.parseSimpleJson(resultString,SelfTableCodeResult.class);
                        if(selfTableCodeResult.isSuccess()){
                            SelfTableCodeOutPara selfTableCodeOutPara = selfTableCodeResult.getResult();
                            double consumeMoney = selfTableCodeOutPara.getConsumeMoney();// 总价
                            String openTime = selfTableCodeOutPara.getOpenTime();// 开卡时间
                            Log.d("JgActivity", "总价:" + consumeMoney + "");
                            Log.d("JgActivity", "开手牌时间:" + openTime + "");
                            List<SelfConsumeRecord> selfConsumeRecords = selfTableCodeOutPara.getLstconsume();
                            if(selfConsumeRecords.size() > 0){
                                setBillLayout(selfConsumeRecords,consumeMoney);
                            }else{
                                billIsNoneTips.setVisibility(View.VISIBLE);
                            }
                        }
                        loadingDialog.close();
                    }
                    break;
                case 2:
                    loadingDialog.close();
                    swipeCardUtils.cancelBandNo(false);
                    dismiss();
                    CustomToast customToast = CustomToast.makeText(MyApplication.getContext(),"网络异常，请呼叫服务员处理！",Toast.LENGTH_LONG,false);
                    customToast.setGravity(Gravity.CENTER,0,0);
                    customToast.showMyToast(5000);
                    break;
                default:
                    break;
            }
        }
    };
    private TextView billTips;
    private TextView swipeHandCard;

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            // 设置Dialog宽度占比为60%，高度为wrap_content
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.6), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        Window window = dialog.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.windowAnimations = R.style.customDialogAnim;
        window.setAttributes(layoutParams);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        Bundle bundle = getArguments();
        cashierIP = bundle.getString("cashierIP");
        cashierPORT = bundle.getString("cashierPORT");
        tvName = bundle.getString("tvName");
        categoryName = bundle.getString("categoryName");

        View view = inflater.inflate(R.layout.jg_query_bill_layout,container,false);
        ImageButton queryBillClose = view.findViewById(R.id.query_bill_close);
        goodsBillListView = view.findViewById(R.id.goods_bill_listview);
        goodsBillListView.setVerticalScrollBarEnabled(false);

        handCard = view.findViewById(R.id.hand_card);
        totalPrice = view.findViewById(R.id.total_price);
        totalTips = view.findViewById(R.id.total_tips);
        billTips = view.findViewById(R.id.bill_tips);
        billIsNoneTips = view.findViewById(R.id.bill_is_none_tips);
        swipeHandCard = view.findViewById(R.id.swipe_hand_card);

        swipeCardUtils = new SwipeCardUtils();
        swipeCardUtils.setOnSwipeCardListener(this);
        swipeCardUtils.swipecard();

        queryBillClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swipeCardUtils.cancelBandNo(false);
                dismiss();
            }
        });

        return view;
    }

    @Override
    public void swipeCardListener(String cardId) {
        Log.d("JgActivity","getBandNo---" + cardId);
        cardIdHex = new DecToHexUtils().getDecToHex(cardId);
        Log.d("JgActivity","getBandNo---" + cardIdHex);
        loadingDialog = new CustomLoadingDialog(getActivity(),"手牌验证中...");
        loadingDialog.show();
        cardIdToCardNo();
    }

    // 调用手牌ID转手牌号接口
    public void cardIdToCardNo(){
        TableChipPara tableChipPara = new TableChipPara();
        tableChipPara.setTableChipId(cardIdHex);
        Gson gson = new Gson();
        String jsonString = gson.toJson(tableChipPara);
        String url = "http://" + cashierIP + ":" + cashierPORT + "/TsInterface/Ts_GetTableCodeByChipId";
        OkHttpUtils.getInstance().postJsonResource(jsonString,url,handler,judgeNum[0]);
    }

    // 调用账单查询接口
    public void queryBill(String tableCode){
        SelfTableCodeInPara selfTableCodeInPara = new SelfTableCodeInPara();
        selfTableCodeInPara.setTableCode(tableCode);
        selfTableCodeInPara.setDepartmentName(categoryName);
        Gson gson = new Gson();
        String jsonString = gson.toJson(selfTableCodeInPara);
        Log.d("JgActivity","账单查询接口调用" + jsonString);
        String url = "http://" + cashierIP + ":" + cashierPORT + "/TsInterface/Ts_QueryKeyConsume";
        OkHttpUtils.getInstance().postJsonResource(jsonString,url,handler,judgeNum[1]);
    }

    public void setBillLayout(List<SelfConsumeRecord> selfConsumeRecords,double consumeMoney){
        MassageBillAdapter billAdapter = new MassageBillAdapter(MyApplication.getContext(),selfConsumeRecords);
        goodsBillListView.setAdapter(billAdapter);
        handCard.setText("手牌号:" + tableCode);
        totalTips.setVisibility(View.VISIBLE);
        billTips.setVisibility(View.VISIBLE);
        totalPrice.setText("￥" + consumeMoney + "元");
        swipeHandCard.setVisibility(View.GONE);
    }
}
